#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDir>
#include <QStandardPaths>
#include <QDateTime>
#include <QFileDialog>
#include <QFile>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , udpSocket(new QUdpSocket(this))
    , frameCount(0)
    , frameRate(0.0)
    , fpsUpdateTimer(new QTimer(this))
    , serverPort(5000)
    , isConnected(false)
    , isStreaming(false)
{
    ui->setupUi(this);

    // 加载设置
    loadSettings();

    // 初始化UI
    ui->statusLabel->setText(tr("未连接"));
    ui->fpsLabel->setText(tr("帧率: 0.0"));
    ui->photoPathEdit->setText(serverPhotoSavePath);
    ui->photoPathEdit_2->setText(clientPhotoSavePath);
    ui->videoDisplay->setAlignment(Qt::AlignCenter);
    ui->videoDisplay->setText(tr("等待连接..."));

    // 连接信号槽
    connect(ui->connectButton, &QPushButton::clicked, this, &MainWindow::onConnectClicked);
    connect(ui->disconnectButton, &QPushButton::clicked, this, &MainWindow::onDisconnectClicked);
    connect(ui->startButton, &QPushButton::clicked, this, &MainWindow::onStartStreamClicked);
    connect(ui->stopButton, &QPushButton::clicked, this, &MainWindow::onStopStreamClicked);
    connect(ui->captureButton, &QPushButton::clicked, this, &MainWindow::onCaptureClicked);
    connect(ui->saveLocationButton, &QPushButton::clicked, this, &MainWindow::onServerSaveLocationClicked);
    connect(ui->saveLocationButton_2,&QPushButton::clicked, this, &MainWindow::onClientSaveLocationClicked);
    connect(udpSocket, &QUdpSocket::readyRead, this, &MainWindow::readPendingDatagrams);

    // 帧率更新定时器
    connect(fpsUpdateTimer, &QTimer::timeout, this, &MainWindow::updateFrameRateDisplay);
    fpsUpdateTimer->start(200); // 每200ms更新一次帧率显示

    // 启动帧率计时器
    frameRateTimer.start();

    // 禁用未连接时的控制按钮
    ui->disconnectButton->setEnabled(false);
    ui->startButton->setEnabled(false);
    ui->stopButton->setEnabled(false);
    ui->captureButton->setEnabled(false);
}

MainWindow::~MainWindow()
{
    disconnectFromServer();
    saveSettings();
    delete ui;
}

void MainWindow::onConnectClicked()
{
    connectToServer();
}

void MainWindow::onDisconnectClicked()
{
    disconnectFromServer();
}

void MainWindow::onStartStreamClicked()
{
    if (isConnected) {
        sendCommand("get_stream");
        isStreaming = true;
        ui->videoDisplay->setText(tr("正在接收视频流..."));
        logMessage(tr("已请求视频流"));

        ui->startButton->setEnabled(false);
        ui->stopButton->setEnabled(true);
        ui->captureButton->setEnabled(true);
    }
}

void MainWindow::onStopStreamClicked()
{
    if (isConnected && isStreaming) {
        sendCommand("stop_stream");
        isStreaming = false;
        ui->videoDisplay->setText(tr("视频流已停止"));
        logMessage(tr("已停止视频流"));

        ui->startButton->setEnabled(true);
        ui->stopButton->setEnabled(false);
        ui->captureButton->setEnabled(false);
    }
}

void MainWindow::onCaptureClicked()
{
    if (!isConnected)
        return;

    // 保存客户端本地图片
    if (ui->videoDisplay->pixmap()) {
        QPixmap displayPixmap = ui->videoDisplay->pixmap()->copy();
        savePhotoToLocal(displayPixmap.toImage());

        // 在照片显示控件中显示
        ui->photoDisplay->setPixmap(displayPixmap.scaled(
            ui->photoDisplay->size(),
            Qt::KeepAspectRatio,
            Qt::SmoothTransformation
        ));
    }

    // 发送保存指令到服务器
    QDateTime dt = QDateTime::currentDateTime();
    QString time = dt.toString("yyyy-MM-dd_hh-mm-ss_t") + ".jpg";

    QString savePath = ui->photoPathEdit->text().trimmed();
    if (!savePath.isEmpty()) {
        sendCommand("get_photo " + savePath + time);
        logMessage(tr("照片捕获请求已发送: %1").arg(savePath + time));
    } else {
        sendCommand("get_photo");
        logMessage(tr("照片捕获请求已发送 (自动命名)"));
    }
}

void MainWindow::onClientSaveLocationClicked()
{
    //客户端保存目录
    QString clientPath = QFileDialog::getExistingDirectory(this,
                        tr("选择照片保存位置"),
                        QDir::homePath());

        if (!clientPath.isEmpty()) {
            clientPhotoSavePath = clientPath;
            ui->photoPathEdit_2->setText(clientPhotoSavePath);
        }
}

void MainWindow::onServerSaveLocationClicked()
{
    //服务端默认保存目录
    QString serverPath = "/home/hq/Pictures/";

    if (!serverPath.isEmpty()) {
        serverPhotoSavePath = serverPath;
        if (!serverPhotoSavePath.endsWith('/') && !serverPhotoSavePath.endsWith('\\'))
            serverPhotoSavePath += '/';

        ui->photoPathEdit->setText(serverPhotoSavePath);
    }

}


void MainWindow::savePhotoToLocal(const QImage &image)
{
    if (image.isNull()) {
        logMessage(tr("错误: 无效的截图图像"));
        return;
    }

    QDateTime dt = QDateTime::currentDateTime();
    QString time = dt.toString("yyyy-MM-dd_hh-mm-ss_t") + ".jpg";

    //QString saveDir = QDir::homePath() + "/Desktop/save";
    QString saveDir = ui->photoPathEdit_2->text().trimmed();
    QDir dir(saveDir);
    if (!dir.exists()) {
        dir.mkpath(saveDir);
    }

    // 拼接文件路径
    QString filePath = saveDir + "/" + time;

    // 保存图片
    if (image.save(filePath, "JPG")) {
        logMessage(tr("图片已保存到本地: %1").arg(filePath));
    } else {
        logMessage(tr("错误: 无法保存图片到 %1").arg(filePath));
    }
}


void MainWindow::connectToServer()
{
    // 验证输入
    QString serverAddressStr = ui->serverAddressEdit->text().trimmed();
    serverPort = ui->serverPortSpin->value();

    if (serverAddressStr.isEmpty()) {
        logMessage(tr("错误: 服务器地址不能为空"));
        return;
    }

    serverAddress = QHostAddress(serverAddressStr);
    if (serverAddress.isNull()) {
        logMessage(tr("错误: 无效的服务器地址"));
        return;
    }

    // 绑定本地UDP端口
    if (!udpSocket->bind()) {
        QString lastError = udpSocket->errorString();
        logMessage(tr("绑定错误: ") + lastError);
        return;
    }

    isConnected = true;
    logMessage(tr("已连接到服务器: %1:%2").arg(serverAddress.toString()).arg(serverPort));
    updateConnectionStatus();

    // 启用控制按钮
    ui->disconnectButton->setEnabled(true);
    ui->connectButton->setEnabled(false);
    ui->startButton->setEnabled(true);
    ui->stopButton->setEnabled(false);
    ui->captureButton->setEnabled(false);
}

void MainWindow::disconnectFromServer()
{
    if (isConnected) {
        // 先停止视频流
        if (isStreaming) {
            sendCommand("stop_stream");
            isStreaming = false;
        }

        udpSocket->close();
        isConnected = false;
        logMessage(tr("已断开连接"));
        updateConnectionStatus();

        // 重置显示
        ui->videoDisplay->setText(tr("已断开连接"));
        ui->fpsLabel->setText(tr("帧率: 0.0"));
        frameCount = 0;

        // 禁用控制按钮
        ui->disconnectButton->setEnabled(false);
        ui->connectButton->setEnabled(true);
        ui->startButton->setEnabled(false);
        ui->stopButton->setEnabled(false);
        ui->captureButton->setEnabled(false);
    }
}

void MainWindow::sendCommand(const QString &command)
{
    if (isConnected) {
        QByteArray data = command.toUtf8();
        udpSocket->writeDatagram(data, serverAddress, serverPort);
    }
}

void MainWindow::readPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
        // 使用传统的readDatagram方法兼容旧版本Qt
        QByteArray data;
        data.resize(udpSocket->pendingDatagramSize());
        QHostAddress senderAddress;
        quint16 senderPort;

        qint64 bytesRead = udpSocket->readDatagram(
            data.data(),
            data.size(),
            &senderAddress,
            &senderPort
        );

        if (bytesRead == -1) {
            logMessage(tr("错误: 读取数据报失败"));
            continue;
        }

        QImage image;
        if (image.loadFromData(data)) {
            frameCount++; // 每成功显示一帧就增加计数

            QPixmap pixmap = QPixmap::fromImage(image);
            // 保持宽高比缩放
            pixmap = pixmap.scaled(
                ui->videoDisplay->size(),
                Qt::KeepAspectRatio,
                Qt::SmoothTransformation
            );
            ui->videoDisplay->setPixmap(pixmap);
        } /*else {
            logMessage(tr("错误: 无法解码图像数据"));
        }*/
    }
}



// 优化后的帧率更新函数
void MainWindow::updateFrameRateDisplay()
{
    // 计算经过的时间（毫秒）
    qint64 elapsedMs = frameRateTimer.restart();

    if (elapsedMs > 0 && frameCount > 0) {
        // 计算当前帧率 (帧数 / (秒))
        double currentFPS = frameCount * 1000.0 / elapsedMs;

        // 应用指数移动平均（EMA）平滑
        frameRate = (frameRate * 0.7) + (currentFPS * 0.3);

        // 更新UI显示
        ui->fpsLabel->setText(tr("帧率: %1").arg(QString::number(frameRate, 'f', 1)));
    } else if (!isConnected) {
        ui->fpsLabel->setText(tr("帧率: 0.0"));
    }

    // 重置帧计数
    frameCount = 0;

    // 重启计时器
    frameRateTimer.start();
}

// 优化后的连接状态更新
void MainWindow::updateConnectionStatus()
{
    ui->statusLabel->setText(
        isConnected ?
        tr("已连接: %1:%2").arg(serverAddress.toString()).arg(serverPort) :
        tr("未连接")
    );
}

void MainWindow::logMessage(const QString &message)
{
    ui->logText->appendPlainText(QTime::currentTime().toString("[hh:mm:ss] ") + message);
}

void MainWindow::loadSettings()
{
    QSettings settings("MyCompany", "UDPVideoStreamClient");

    ui->serverAddressEdit->setText(settings.value("server/address", "127.0.0.1").toString());
    ui->serverPortSpin->setValue(settings.value("server/port", 8888).toInt());
    serverPhotoSavePath = settings.value("photos/path", QDir::homePath() + "/Pictures/").toString();
    clientPhotoSavePath = settings.value("photos/clientpath", QDir::homePath() + "/Pictures/").toString();

}

void MainWindow::saveSettings()
{
    QSettings settings("MyCompany", "UDPVideoStreamClient");

    settings.setValue("server/address", ui->serverAddressEdit->text());
    settings.setValue("server/port", ui->serverPortSpin->value());
    settings.setValue("photos/path", serverPhotoSavePath);
    settings.setValue("photos/clientpath",clientPhotoSavePath);
}
